# -*- coding: utf-8 -*-

# Created on 06/08/2010

# Copyright (C) 2010  Sergio Rodrigo

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import pygame

from core.Component import STATE_PRESSED

class Peripheral:
    """ Generic peripheral.
    
    Should be subclassed.
    
    """

    def __init__(self):
        self.components = []
        self.__dataBuffer = []

    def initialize(self):
        pass

    def addComponent(self, component):
        """ Adds a component.
        
        component -- Component object
        
        """
        self.components.append(component)

    def update(self):
        """ Updates de peripheral.
        
        """
        #    Se hace de esta forma para evitar recorrer varias veces la lista
        # pygame.event.get(), que ralentiza el proceso.
        for event in pygame.event.get():
            for c in self.components:
                c.update(event)
        self.__makeData()

    def __makeData(self):
        """ Builds and appends data used in Control to make actions.
        Usage:

        for c in self.components:
            read state
            make data tuple with value and magnitude
            append to dataBuffer list
            
        """
        for c in self.components:
            if c.currentState == STATE_PRESSED:
                data = (c.value, c.magnitude)
                self.__dataBuffer.append(data)

    def readData(self):
        """ Reads, returns and pops one element from the buffer.
        
        return value -- (value, magnitude)
        
        """
        return self.__dataBuffer.pop(0) if self.__dataBuffer else None

# eof
